package com.epfresh.fragment;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.HomeActivity;
import com.epfresh.activity.LoginActivity;
import com.epfresh.activity.SearchGoodsActivity;
import com.epfresh.adapter.SearchGoodsViewBinder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.MsgView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.tablayout.utils.UnreadMsgUtils;
import com.epfresh.bean.AddCarResponse;
import com.epfresh.bean.CarCntResponse;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.ListGoods;
import com.epfresh.global.BaseFragment;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.FakeAddImageView;
import com.epfresh.views.MultiStateView;
import com.epfresh.views.PointFTypeEvaluator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

public class SearchGoodsFragment extends BaseFragment {
    private ViewGroup rl;
    private PtrFrameLayout ptrFrameLayout;
    private MultiStateView msv_view;
    private RecyclerView rv_goods_list;

    private MultiTypeAdapter multiAdapter;
    private List<Object> items = new ArrayList<>();
    private LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();

    private int pageNum;
    private String keyWords;
    private String marketId;

    private boolean isFirstLoad = true;

    private List<ListGoods> content;
    private ImageView img_cart;
    private MsgView msg;

    private boolean isRefresh = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_search_goods, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public String getBaseTag() {
        return "SearchGoodsFragment";
    }

    public void setData(String keyWords,String marketId) {
        this.keyWords=keyWords;
        this.marketId=marketId;
    }

    private void initView(View view) {
        rl = view.findViewById(R.id.rl);
        img_cart = view.findViewById(R.id.img_cart);
        img_cart.setOnClickListener(this);
        msg = view.findViewById(R.id.msg1);
        ptrFrameLayout = view.findViewById(R.id.ptr_frame_layout);
        msv_view = view.findViewById(R.id.msv_view);
        rv_goods_list = view.findViewById(R.id.rv_goods_list);

        msv_view.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        msv_view.setViewForState(R.layout.empty_goods, MultiStateView.VIEW_STATE_EMPTY);
        msv_view.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);

        multiAdapter = new MultiTypeAdapter();
        ptrFrameLayout.setPtrHandler(ptrHandler);

        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreDelegate.attach(rv_goods_list, loadMoreSubject);

        SearchGoodsViewBinder searchGoodsViewBinder = new SearchGoodsViewBinder(getContext());
        searchGoodsViewBinder.setOnCartClickListener(new SearchGoodsViewBinder.OnCartClickListener() {
            @Override
            public void OnCartClick(int type, ListGoods item, View view) {
                switch (type) {
                    case 0:
                        addCartCnt(item, true);//添加
                        addAnim(view);
                        break;
                    case 1:
                        addCartCnt(item, false);//减少
                        break;
                    case 2:
                        Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                        intent.putExtra("id", item.getId());
                        intent.putExtra("storeId", item.getStoreId());
                        intent.putExtra("promotionItemId", item.getPromotionItemId());
                        startActivity(intent);
                        break;
                }
            }
        });

        multiAdapter.register(ListGoods.class, searchGoodsViewBinder);
        multiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        multiAdapter.setItems(items);

        rv_goods_list.setLayoutManager(new LinearLayoutManager(getContext()));
        rv_goods_list.setAdapter(multiAdapter);

        refresh();
    }

    /**
     * 刷新
     */
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv_goods_list, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    /**
     * 加载更多
     */
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMore();
        }
    };

    private void refresh() {
        isRefresh = true;
        items.clear();
        pageNum = 0;
        reqGoodsSearchResult();
    }

    private void loadMore() {
        isRefresh = false;
        pageNum += 1;
        reqGoodsSearchResult();
    }

    private void reqGoodsSearchResult() {
        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(AppPurchaseRouterConstant.cmd_store_product_list);
        requestEntityMap.putParameter("sortDirection", "DESC");
        requestEntityMap.putParameter("title", keyWords);
        requestEntityMap.putParameter("pageNumber", pageNum);
        requestEntityMap.putParameter("pageSize", 10);
        requestEntityMap.putParameter("sortProperty", "modifiedTime");
        if (marketId != null) {
            String[] strings = new String[1];
            strings[0] = marketId;
            requestEntityMap.putParameter("marketIds", strings);
        }

        request(requestEntityMap, AppPurchaseRouterConstant.cmd_store_product_list, new OnRequestListener<ContentEntity<ListGoods>>() {
            @Override
            public ContentEntity<ListGoods> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<ListGoods>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                ptrFrameLayout.refreshComplete();
                msv_view.setViewState(MultiStateView.VIEW_STATE_ERROR);
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                ptrFrameLayout.refreshComplete();
                msv_view.setViewState(MultiStateView.VIEW_STATE_ERROR);
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {
                if (isFirstLoad) {
                    msv_view.setViewState(MultiStateView.VIEW_STATE_LOADING);
                    isFirstLoad = false;
                }
            }

            @Override
            public void onResponse(ResponseEntity<ContentEntity<ListGoods>> response, Object tag) {
                msv_view.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                ptrFrameLayout.refreshComplete();
                requestCount();

                ContentEntity<ListGoods> responseElement = response.getResponseElement();
                content = responseElement.getContent();
                if (content != null) {
                    if (content.size() > 0) {
                        loadMoreDelegate.addAllItem(items, content);
                        if (content.size() < 10) {
                            loadMoreDelegate.setStatusNoMore();
                        } else {//等于10
                            loadMoreDelegate.setStatusNormal();
                        }
                    } else {
                        if (isRefresh) {
                            msv_view.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                        loadMoreDelegate.setStatusNoMore();
                    }
                }
            }
        });
    }

    public void requestCount() {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_order_cart_cnt);
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        re.putParameter("wholeSalesType", "1");
        ApplicationHelper.getInstance().requestSilent(re, AppPurchaseRouterConstant.cmd_order_cart_cnt, onCartCntRequestListener);
    }

    OnRequestListener<CarCntResponse> onCartCntRequestListener = new OnRequestListener<CarCntResponse>() {
        @Override
        public CarCntResponse jsonToObj(String s) {
            return new Gson().fromJson(s, CarCntResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<CarCntResponse> responseEntity, Object o) {
            CarCntResponse carCntResponse = responseEntity.getResponseElement();
            if (carCntResponse != null) {
                carCntResponse.init();

                for (ListGoods listGoods : content) {
                    double goodsCount = carCntResponse.getGoodsCount(listGoods.getIdPlus());
                    listGoods.setCount(goodsCount);
                }
                if (carCntResponse.getShoppingCarCnt() > 0) {
                    UnreadMsgUtils.show(msg, 0, true, true);
                } else {
                    UnreadMsgUtils.show(msg, 0, false, true);
                }

            }
            multiAdapter.notifyDataSetChanged();

        }
    };

    public void addCartCnt(ListGoods goods, boolean isAdd) {
        double min = goods.getMoq();
        double incr = goods.getIncr();
        double amount = goods.getCount();


        if (isAdd) {
            amount = FormatUtil.countAdd(amount, incr);
        } else {
            amount = FormatUtil.countAdd(amount, -incr);
        }

        if (FormatUtil.remainderZero(amount, goods.getInventoryAmount()) > 0) {
            amount = goods.getInventoryAmount();
            T.toast("库存不足");
        } else if (isAdd) {
//            addAnim(v);
        }
        if (isAdd && FormatUtil.remainderZero(amount, goods.getMoq()) < 0) {
            amount = min;
        }


        if (!isAdd && (FormatUtil.remainderZero(amount, 0) <= 0 || FormatUtil.remainderZero(amount, min) < 0)) {
            amount = 0;
            reqCartCnt(amount, goods);
            return;
        }
        amount = FormatUtil.countFormat(amount, incr, min, goods.getInventoryAmount());
        reqCartCnt(amount, goods);


    }

    private void reqCartCnt(double productCount, ListGoods goods) {
        if (goods == null) {
            return;
        }
        goods.setCount(productCount);
        multiAdapter.notifyDataSetChanged();

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_order_cart_add);
        re.putParameter("specId", goods.getProductSpecPrice().getProductSpecId());
        if (goods.getPromotion() != null)
            re.putParameter("specPromotionItemId", goods.getPromotion().getItemId());
        re.putParameter("count", productCount);

        request(re, AppPurchaseRouterConstant.cmd_order_cart_add, new OnRequestListener<AddCarResponse>() {
            @Override
            public AddCarResponse jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, AddCarResponse.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<AddCarResponse> response, Object tag) {
                if (response.getResponseElement() != null) {
                    if (response.getResponseElement().getshoppingCarCnt() > 0) {
                        UnreadMsgUtils.show(msg, 0, true, true);
                    } else {
                        UnreadMsgUtils.show(msg, 0, false, true);
                    }
                }
            }
        });
    }


    /**
     * 加购物车动画
     *
     * @param view
     */
    public void addAnim(View view) {
        int[] addLocation = new int[2];
        int[] cartLocation = new int[2];
        view.getLocationInWindow(addLocation);
        img_cart.getLocationInWindow(cartLocation);

        PointF startP = new PointF();
        PointF endP = new PointF();
        PointF controlP = new PointF();

        startP.x = addLocation[0] + LocalDisplay.dp2px(10);
        startP.y = addLocation[1] - LocalDisplay.dp2px(24) - LocalDisplay.getStatusBarHeight(getContext()) - LocalDisplay.dp2px(10);
        endP.x = cartLocation[0] + LocalDisplay.dp2px(20);
        endP.y = cartLocation[1] - LocalDisplay.dp2px(25) - LocalDisplay.getStatusBarHeight(getContext());
        controlP.x = endP.x;
        controlP.y = startP.y;

        final FakeAddImageView fakeAddImageView = new FakeAddImageView(getContext());
        rl.addView(fakeAddImageView);
        fakeAddImageView.setImageResource(R.drawable.cart_bezier);
        fakeAddImageView.getLayoutParams().width = LocalDisplay.dp2px(10);
        fakeAddImageView.getLayoutParams().height = LocalDisplay.dp2px(10);
        fakeAddImageView.setVisibility(View.VISIBLE);
        ObjectAnimator addAnimator = ObjectAnimator.ofObject(fakeAddImageView, "mPointF",
                new PointFTypeEvaluator(controlP), startP, endP);
        addAnimator.setInterpolator(new AccelerateInterpolator());
        addAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                fakeAddImageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                fakeAddImageView.setVisibility(View.GONE);
                rl.removeView(fakeAddImageView);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(img_cart, "scaleX", 0.8f, 1.0f);
        ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(img_cart, "scaleY", 0.8f, 1.0f);
        scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
        scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator);
        animatorSet.setDuration(700);
        animatorSet.start();

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_search:
            case R.id.ll_search:
            case R.id.img_cart:
                if (ApplicationHelper.getInstance().getUser().getAccess_token() == null) {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                } else {
                    Intent intent = new Intent(getContext(),HomeActivity.class);
                    intent.putExtra("from","searchGoodsActivity");
                    startActivity(intent);
                }
                break;
        }
    }
}
